<template>
  <div class="atomic-git-task-container">
    <el-card class="task-header-card">
      <div class="task-header">
        <div class="task-title">
          <h2>{{ task.name }}</h2>
          <el-tag :type="getStatusType(task.status)" size="small">{{ task.status }}</el-tag>
        </div>
        <div class="task-actions">
          <el-button-group>
            <el-button type="primary" size="small" @click="goBack">
              <el-icon><Back /></el-icon> 返回
            </el-button>
            <el-button type="success" size="small" @click="markAsCompleted" :disabled="isTaskCompleted">
              <el-icon><Check /></el-icon> 标记完成
            </el-button>
          </el-button-group>
        </div>
      </div>
      
      <div class="task-info">
        <div class="info-item">
          <span class="label">任务ID:</span>
          <span>{{ task.id }}</span>
        </div>
        <div class="info-item">
          <span class="label">创建时间:</span>
          <span>{{ formatDate(task.created_at) }}</span>
        </div>
        <div class="info-item">
          <span class="label">截止时间:</span>
          <span>{{ formatDate(task.due_date) }}</span>
        </div>
        <div class="info-item">
          <span class="label">预计工时:</span>
          <span>{{ task.estimated_hours }} 小时</span>
        </div>
        <div class="info-item">
          <span class="label">分配给:</span>
          <span>{{ task.assigned_to || '未分配' }}</span>
        </div>
        <div class="info-item git-repo-item">
          <span class="label">Git仓库:</span>
          <span>
            <template v-if="task.project && task.project.git_repository_url">
              <el-tag size="small" type="success">{{ task.project.git_repository_url }}</el-tag>
            </template>
            <template v-else>
              <el-tag size="small" type="warning">未设置仓库URL</el-tag>
            </template>
          </span>
        </div>
        <div class="info-item git-repo-item">
          <span class="label">本地路径:</span>
          <span>
            <template v-if="task.project && task.project.project_folder_path">
              <el-tag size="small" type="success">{{ task.project.project_folder_path }}</el-tag>
            </template>
            <template v-else>
              <el-tag size="small" type="warning">未设置本地路径</el-tag>
            </template>
          </span>
        </div>
      </div>
      
      <div class="task-description">
        <h3>任务描述</h3>
        <div v-html="renderedDescription" class="description-content"></div>
      </div>
    </el-card>
    
    <el-divider content-position="center">Git 操作</el-divider>
    
    <GitOperations 
      :defaultRepoPath="repoPath" 
      :taskId="taskId"
      :gitRepoUrl="gitRepoUrl"
      :projectId="projectId"
      @git-operation-completed="handleGitOperationCompleted"
    />
    
    <el-divider content-position="center">执行记录</el-divider>
    
    <el-card class="execution-history-card">
      <template #header>
        <div class="card-header">
          <span>执行历史</span>
          <el-button size="small" @click="loadExecutionHistory">刷新</el-button>
        </div>
      </template>
      
      <div v-if="isLoadingExecutions" class="loading-container">
        <el-skeleton :rows="3" animated />
      </div>
      
      <el-empty v-else-if="!executionHistory.length" description="暂无执行记录" />
      
      <el-timeline v-else>
        <el-timeline-item
          v-for="execution in executionHistory"
          :key="execution.id"
          :timestamp="formatDate(execution.execution_time)"
          :type="getExecutionStatusType(execution.status)"
        >
          <div class="execution-item">
            <div class="execution-header">
              <div class="execution-title">
                <span class="execution-action">{{ getExecutionActionName(execution.action) }}</span>
                <el-tag size="small" :type="getExecutionStatusType(execution.status)">
                  {{ execution.status }}
                </el-tag>
              </div>
              <div class="execution-executor">
                <span>执行者: {{ execution.executor || '系统' }}</span>
              </div>
            </div>
            
            <div v-if="execution.result" class="execution-result">
              <pre>{{ execution.result }}</pre>
            </div>
            
            <div v-if="execution.review_status" class="execution-review">
              <div class="review-header">
                <span class="review-label">评审:</span>
                <el-tag size="small" :type="getReviewStatusType(execution.review_status)">
                  {{ execution.review_status }}
                </el-tag>
              </div>
              <div v-if="execution.review_comment" class="review-comment">
                {{ execution.review_comment }}
              </div>
            </div>
          </div>
        </el-timeline-item>
      </el-timeline>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import { getTaskDetail, updateTask, executeTask, getSubtaskGitInfo } from '../../api/index';
import api from '../../api/index';
import GitOperations from '../../components/GitOperations.vue';
import { Back, Check } from '@element-plus/icons-vue';
import { marked } from 'marked';

export default {
  name: 'GitTaskDetail',
  components: {
    GitOperations,
    Back,
    Check
  },
  setup() {
    const route = useRoute();
    const router = useRouter();
    const taskId = parseInt(route.params.id);
    
    // 任务数据
    const task = ref({});
    const isLoading = ref(false);
    const repoPath = ref('');
    const gitRepoUrl = ref('');
    const projectId = ref('');
    
    // 执行历史
    const executionHistory = ref([]);
    const isLoadingExecutions = ref(false);
    
    // 计算属性
    const isTaskCompleted = computed(() => {
      return task.value.status === 'COMPLETED' || task.value.status === 'REVIEWED';
    });
    
    const renderedDescription = computed(() => {
      return task.value.description ? marked(task.value.description) : '';
    });
    
    // 方法
    const loadTaskDetail = async () => {
      isLoading.value = true;
      try {
        // 从URL中获取任务ID和类型
        const taskType = route.query.type || 'main'; // 默认为主任务
        
        let response;
        
        if (taskType === 'sub') {
          // 如果是子任务，使用子任务Git信息API
          console.log('正在加载子任务Git信息，任务ID:', taskId);
          response = await getSubtaskGitInfo(taskId);
          
          if (response.data && response.data.data) {
            // 构造任务对象
            const gitInfo = response.data.data;
            task.value = {
              id: gitInfo.subtask.id,
              name: gitInfo.subtask.title,
              description: gitInfo.subtask.description,
              status: gitInfo.subtask.status,
              // 从主任务和项目中获取仓库信息
              project: {
                id: gitInfo.project.id,
                name: gitInfo.project.name,
                git_repository_url: gitInfo.project.git_repository_url,
                project_folder_path: gitInfo.project.project_folder_path
              },
              // 如果主任务有指定仓库路径，也记录下来
              repository_path: gitInfo.main_task.repository_path
            };
            
            console.log('成功获取子任务Git信息:', task.value);
          } else {
            throw new Error('无效的子任务Git信息格式');
          }
        } else {
          // 如果是主任务，使用主任务API
          response = await getTaskDetail(taskId);
          
          // 检查API响应格式
          if (response.data && response.data.data) {
            task.value = response.data.data;
          } else if (response.data) {
            task.value = response.data; // 直接使用响应数据
          } else {
            throw new Error('无效的任务数据格式');
          }
        }
        
        // 设置Git操作的路径 - 优先使用项目本地文件夹路径
        if (task.value.project && task.value.project.project_folder_path) {
          repoPath.value = task.value.project.project_folder_path;
          console.log('使用项目本地文件夹路径:', repoPath.value);
        } 
        // 如果项目没有设置本地路径，尝试从任务获取
        else if (task.value.repository_path) {
          repoPath.value = task.value.repository_path;
          console.log('使用任务Git仓库路径:', repoPath.value);
        } 
        // 如果都没有，显示错误信息
        else {
          console.warn('未找到项目的本地文件夹路径');
          ElMessage.warning('未找到项目的本地文件夹路径，请在项目设置中配置本地仓库路径');
        }
        
        // 添加远程仓库URL信息到上下文
        gitRepoUrl.value = task.value.project?.git_repository_url || '';
        
        // 如果有仓库路径，尝试自动刷新Git状态
        if (repoPath.value) {
          setTimeout(() => {
            // 直接告知GitOperations组件刷新状态
            window.dispatchEvent(new CustomEvent('git-refresh-status'));
          }, 500);
        }
      } catch (error) {
        console.error('加载任务详情失败:', error);
        ElMessage.error(`加载任务详情失败: ${error.message || '服务器错误'}`);
      } finally {
        isLoading.value = false;
      }
    };
    
    const loadExecutionHistory = async () => {
      isLoadingExecutions.value = true;
      try {
        // 这里应该使用真实的API来获取任务的执行历史
        // const response = await getTaskExecutions(taskId);
        // executionHistory.value = response.data.data;
        
        // 模拟数据
        executionHistory.value = [
          {
            id: 1,
            task_id: taskId,
            action: 'git_commit',
            status: 'SUCCESS',
            result: 'Added feature XYZ\n1 file changed, 30 insertions(+), 5 deletions(-)',
            execution_time: new Date().toISOString(),
            executor: 'developer1',
            review_status: 'APPROVED',
            review_comment: '代码符合规范，提交信息清晰'
          },
          {
            id: 2,
            task_id: taskId,
            action: 'git_push',
            status: 'SUCCESS',
            result: 'Pushed to origin/main',
            execution_time: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
            executor: 'developer1'
          }
        ];
      } catch (error) {
        console.error('加载执行历史失败:', error);
        ElMessage.error('加载执行历史失败');
      } finally {
        isLoadingExecutions.value = false;
      }
    };
    
    const markAsCompleted = async () => {
      try {
        await ElMessageBox.confirm(
          '确定要将此任务标记为已完成吗？',
          '确认操作',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        );
        
        const updateData = {
          status: 'COMPLETED'
        };
        
        const response = await updateTask(taskId, updateData);
        
        if (response.data.success) {
          ElMessage.success('任务已标记为完成');
          loadTaskDetail();
        } else {
          ElMessage.error(response.data.message || '操作失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('更新任务状态失败:', error);
          ElMessage.error('更新任务状态失败');
        }
      }
    };
    
    const handleGitOperationCompleted = (result) => {
      // 记录Git操作
      console.log('Git操作完成:', result);
      
      // 记录执行结果
      if (result.success) {
        // 这里可以调用API将Git操作记录到执行历史中
        // 例如: recordTaskExecution(taskId, result)
        
        // 刷新执行历史
        loadExecutionHistory();
      }
    };
    
    const goBack = () => {
      router.back();
    };
    
    // 辅助函数
    const formatDate = (dateString) => {
      if (!dateString) return '未设置';
      
      const date = new Date(dateString);
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      });
    };
    
    const getStatusType = (status) => {
      const statusMap = {
        'TODO': 'info',
        'IN_PROGRESS': 'warning',
        'COMPLETED': 'success',
        'REVIEWED': 'success',
        'BLOCKED': 'danger'
      };
      
      return statusMap[status] || 'info';
    };
    
    const getExecutionStatusType = (status) => {
      const statusMap = {
        'SUCCESS': 'success',
        'FAILED': 'danger',
        'PENDING': 'info',
        'IN_PROGRESS': 'warning'
      };
      
      return statusMap[status] || 'info';
    };
    
    const getReviewStatusType = (status) => {
      const statusMap = {
        'APPROVED': 'success',
        'REJECTED': 'danger',
        'PENDING': 'info'
      };
      
      return statusMap[status] || 'info';
    };
    
    const getExecutionActionName = (action) => {
      const actionMap = {
        'git_commit': 'Git提交',
        'git_push': 'Git推送',
        'git_pull': 'Git拉取',
        'git_add': 'Git添加',
        'git_checkout': 'Git切换分支'
      };
      
      return actionMap[action] || action;
    };
    
    // 生命周期钩子
    onMounted(() => {
      loadTaskDetail();
      loadExecutionHistory();
    });
    
    return {
      taskId,
      task,
      isLoading,
      repoPath,
      gitRepoUrl,
      projectId,
      executionHistory,
      isLoadingExecutions,
      isTaskCompleted,
      renderedDescription,
      loadTaskDetail,
      loadExecutionHistory,
      markAsCompleted,
      handleGitOperationCompleted,
      goBack,
      formatDate,
      getStatusType,
      getExecutionStatusType,
      getReviewStatusType,
      getExecutionActionName
    };
  }
};
</script>

<style scoped>
.atomic-git-task-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.task-header-card {
  margin-bottom: 20px;
}

.task-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.task-title {
  display: flex;
  align-items: center;
  gap: 12px;
}

.task-title h2 {
  margin: 0;
}

.task-info {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 20px;
}

.info-item {
  display: flex;
  gap: 8px;
}

.info-item .label {
  font-weight: bold;
  color: #606266;
}

.git-repo-item {
  margin-top: 10px;
  width: 100%;
}

.git-repo-item .el-tag {
  font-family: monospace;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.task-description {
  margin-top: 16px;
}

.task-description h3 {
  margin-top: 0;
  margin-bottom: 12px;
  font-size: 18px;
}

.description-content {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 16px;
  background-color: #f5f7fa;
}

.execution-history-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.loading-container {
  padding: 20px 0;
}

.execution-item {
  padding: 12px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
  background-color: #fff;
  margin-bottom: 8px;
}

.execution-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.execution-title {
  display: flex;
  align-items: center;
  gap: 8px;
}

.execution-action {
  font-weight: bold;
}

.execution-result {
  margin-top: 8px;
  margin-bottom: 8px;
}

.execution-result pre {
  white-space: pre-wrap;
  background-color: #f5f7fa;
  padding: 8px;
  border-radius: 4px;
  font-family: monospace;
  font-size: 14px;
  max-height: 200px;
  overflow-y: auto;
}

.execution-review {
  margin-top: 12px;
  padding-top: 8px;
  border-top: 1px dashed #ebeef5;
}

.review-header {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 4px;
}

.review-label {
  font-weight: bold;
}

.review-comment {
  margin-top: 4px;
  font-style: italic;
  color: #606266;
}
</style> 
 